var app = getApp()
const util = require('../../utils/util');

Page({
  data: {
    goodsList: [],
    orderRemark: '',
    selectAddress: [],
    selectAddressId: '',
    goods_price: '',
    express_fee: '',
    total_price: '',
    total_payment: '',
    useIntegral: false,
    useCoin: false,
    integral: '',
    coin: '',
    interalDeduction: 0,
    coinDeduction: 0,
    selectModelInfo: {
      models: [],
      price: '',
      buyCount: 1,
    }
  },

  getGoodsList: function () {
    var data = wx.getStorageSync('payinfo')
    
    this.setData({
      goodsList: data
    });
  },
  calculatePrice: function () {
    var that = this;
    var data = that.data.goodsList;
    var goods_price = 0;
    var express_fee = 0;
    var total_payment = 0;

    for (var i = 0; i < data.length; i++) {
      goods_price += parseFloat(data[i].price) * parseInt(data[i].num);
      express_fee += parseFloat(data[i].freight_fee);
    }
    total_payment = goods_price + express_fee;

    that.setData({
      goods_price: goods_price.toFixed(2),
      express_fee: express_fee.toFixed(2),
      total_payment: total_payment.toFixed(2),
      total_price: total_payment.toFixed(2)
    });
  },
  inputBuyCount: function (e) {
    var item = e.currentTarget.dataset.item;
    var selectModelInfo = this.data.selectModelInfo;
    var count = e.detail.value;
    var stock = parseInt(item.total_stock);
    var index = 0;

    if (count >= stock) {
      wx.showModal({
        title: '提示',
        content: '不能超过最大库存数，当前库存数为:' + stock,
      })
      count = 1;
    }
    for (var i = 0; i < this.data.goodsList.length; i++) {
      if (this.data.goodsList[i].goods_id == item.goods_id) {
        index = i;
        break;
      }
    }
    var itemdata = 'goodsList[' + index + '].num';
    this.setData({
      [itemdata]: count
    });
    // this.setData({
    //   'selectModelInfo.buyCount': +count
    // });
    this.calculatePrice();
  },
  clickMinusButton: function (e) {
    var item = e.currentTarget.dataset.item;
    var selectModelInfo = this.data.selectModelInfo;
    var count = parseInt(item.num);
    var stock = parseInt(item.total_stock);
    var index = 0;

    if (count <= 1) {
      return;
    }
    for (var i = 0; i < this.data.goodsList.length; i++) {
      if (this.data.goodsList[i].goods_id == item.goods_id) {
        index = i;
        break;
      }
    }
    var itemdata = 'goodsList[' + index + '].num';
    this.setData({
      //'selectModelInfo.buyCount': count - 1
      ['goodsList[' + index + '].num']: count - 1
    });
    this.calculatePrice();
  },
  clickPlusButton: function (e) {
    var item = e.currentTarget.dataset.item;
    var selectModelInfo = this.data.selectModelInfo;
    var count = parseInt(item.num);
    var stock = parseInt(item.total_stock);
    var index = 0;

    if (count >= stock) {
      return;
    }
    for(var i=0; i<this.data.goodsList.length; i++) {
      if (this.data.goodsList[i].goods_id == item.goods_id) {
        index = i;
        break;
      }
    }
    var itemdata = 'goodsList[' + index + '].num';
    this.setData({
      //'selectModelInfo.buyCount': count + 1
      [itemdata]: count + 1
    });
    this.calculatePrice();
  },

  remarkInput: function (e) {
    var value = e.detail.value;

    this.setData({
      orderRemark: value
    });
  },
  getAddressList: function () {
    let that = this;
    app.get('User/getuseraddress', {
    }, function (res) {
      if (res.code == 200 && res.data.length > 0) {
        var index = 0;
        if (!util.isEmpty(that.data.selectAddressId)) {
          for (var i=0; i<res.data.length; i++) {
            if (res.data[i].address_id == that.data.selectAddressId) {
              index = i;
              break;
            }
          }
        }
        that.setData({
          selectAddress: res.data[index],
        })
      }
    })
  },
  addAddress: function () {
    wx.navigateTo({
      url: '../myAddressEdit/myAddressEdit',
    });
  },
  goToMyAddress: function () {
    var addressId = this.data.selectAddress.id;
    wx.navigateTo({
      url: '../myAddress/myAddress?frompage=order',
    })
  },
  useIntegralChange: function (e) {
    this.setData({
      useIntegral: e.detail.value
    });
    this.recalculateIntegral();
  },
  recalculateIntegral: function() {
    var interalDeduction = parseInt(this.data.integral / 10);
    var total_price = this.data.total_price;
    if (this.data.useIntegral) {
      total_price = total_price -interalDeduction;
    } else {
      total_price = total_price + interalDeduction;
    }
    var total_payment = total_price;
    if (total_payment < 0) total_payment = 0.00;
    this.setData({
      total_price: total_price,
      total_payment: total_payment,
      interalDeduction: interalDeduction
    })
  },
  useCoinChange: function (e) {
    this.setData({
      useCoin: e.detail.value
    });
    this.recalculateCoin();
  },
  recalculateCoin: function () {
    var coinDeduction = parseInt(this.data.coin);
    var total_price = this.data.total_price;
    if (this.data.useCoin) {
      total_price = total_price - coinDeduction;
    } else {
      total_price = total_price + coinDeduction;
    }
    var total_payment = total_price;
    if (total_payment < 0) total_payment = 0.00
    this.setData({
      total_price: total_price,
      total_payment: total_payment,
      coinDeduction: coinDeduction
    })
  },
  getUserInfo: function() {
    let that = this;
    app.get('User/getuserinfo', {
    }, function (res) {
      if (res.code == 200) {
        that.setData({
          integral: res.data.integral,
          coin: res.data.commission_price
        })
      }
    })
  },
  confirmPayment: function() {
    let that = this;
    app.get('Pay/addorder', {
      goods_id: that.data.goodsList[0].goods_id,
      goods_type: that.data.goodsList[0].goods_type,
      quantity: that.data.goodsList[0].num,
      address_id: that.data.selectAddress.address_id,
      total_payment: that.data.total_payment,
      interalDeduction: that.data.interalDeduction,
      coinDeduction: that.data.coinDeduction,
      remark: that.data.orderRemark
    }, function (res) {
      if (res.code == 200) {
        app.get('Pay/reqpay', {
          order_id: res.data
        }, function (reqRes) {
          if (reqRes.code == 200) {
            //发起支付
            var resData = JSON.parse(reqRes.data);
            wx.requestPayment({
              'timeStamp': resData.timeStamp,
              'nonceStr': resData.nonceStr,
              'package': resData.package,
              'signType': resData.signType,
              'paySign': resData.paySign,
              'success': function (res) {
                console.log('[cartDetail.js] pay success.');
              },
              'fail': function (res) {
                console.log('[cartDetail.js] pay fail.');
              },
              'complete': function (res) {
                console.log('[cartDetail.js] pay complete.');
              }
            })
          }
        })
      }
    })
  },
  onLoad: function (options) {
    this.getGoodsList();
    this.calculatePrice();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    this.getAddressList();
    this.getUserInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})